package com.controller;

import com.controller.vo.Node;
import com.pojo.Role;
import com.service.PermissionService;
import com.service.RoleService;
import com.util.Pager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.activation.URLDataSource;
import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

@RestController
@RequestMapping("/sys/role")
public class RoleHandler {
    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;
    @RequestMapping("/searchByRole")
    public Role searchByRole(String rid){
        return roleService.searchByRole(rid);
    }

    @RequestMapping("/tree")
    public List<Node> tree(String rid) {
        return permissionService.search4Tree(rid);
    }

    @RequestMapping("/grant")
    public String grant(String rid, String[] mids) {
        String msg = "授权成功！";
        try {
            permissionService.gran4Role(rid, mids);
        } catch (Exception e) {
            msg = "授权失败！";
        }
        return msg;
    }

    /**
     * 分页查询
     * @param role
     * @param limit
     * @param offset
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/searchPager")
    public Pager<Role> searchPager(Role role,Integer limit,Integer offset) throws UnsupportedEncodingException {
        if(role.getRoleName()!=null){
            URLDecoder.decode(role.getRoleName(),"UTF-8");
        }
        Pager<Role> pager = new Pager<>();
        pager.setLimit(limit);
        pager.setOffSet(offset);
        pager.setCondition(role);
        return roleService.searchRolePager(pager);
    }

    @RequestMapping("/updateRole")
    public String updateRole(Role role){
        String msg="修改失败！";
        int i = roleService.update(role);
        if(i>0){
            msg="修改成功！";
        }
        return msg;
    }

    @RequestMapping("/delRole")
    public String deleteRole(Integer rid){
        String msg="删除失败！";
        int i=roleService.deleteRole(rid);
        if(i>0){
            msg="删除成功！";
        }
        return msg;
    }


    @RequestMapping("/addRole")
    public String addRole(Role role){
        String msg="添加失败！";
        int i=roleService.addRole(role);
        if(i>0){
            msg="添加成功！";
        }
        return msg;
    }


}
